<template>
    <div class="packaging-index yuan-container">
        <a-card title="包装管理">
            <div class="filter-panel">
                <a-input-search class="filter-list" allowClear v-model="keywords" placeholder="请输入关键字" @search="resetList" />
                <a-button type="primary" @click="add" class="filter-list" style="float: right;"
                    v-if="$utilCheckPermission(['packagingManagementAdd'])">新增包装</a-button>

            </div>
            <a-tabs type="card" :default-active-key="0" @change="changeTab">
                <a-tab-pane v-for="(item,i) in tabsData" :key="i" :tab="item.name">
                    <div class="table">
                        <a-table bordered :rowKey="getRowKey" :data-source="pageList" :columns="columns" :pagination="pagination" :loading="loading"></a-table>
                    </div>
                </a-tab-pane>
            </a-tabs>

        </a-card>
        <PackagingAdd :rawType="rawType" :visible="addVisible" @closeModal="() => addVisible = false" :infoId="infoId" @resetList="getList" />
        <PackagingDetail :visible="detailVisible" @closeModal="() => detailVisible = false" :infoData="infoData" />

        <a-modal :visible="addInputVisible" :title="modalOption.title" @ok="modalOption.onOk" :dialog-style="{ top: '20px' }"
                 @cancel="modalOption.onCancel" :okText="modalOption.okText" :cancelText="modalOption.cancelText"
                 :confirmLoading="modalOption.loading"
                 class="yuan-modal packaging-add-modal">
            <a-form-model
                layout="inline"
                class="yuan-form"
                ref="form"
                :model="addInputForm"
                :rules="addInputFormRules"
                :label-col="{ style: { width: '100px' } }"
                :wrapper-col="{ style: { width: 'calc(100% - 120px)' } }">
                <a-form-model-item label="投料量(kg)" prop="putIntoNum">
                    <a-input-number style="width: 200px" v-model="addInputForm.putIntoNum" placeholder="请输入投料量" />
                </a-form-model-item>
            </a-form-model>
        </a-modal>

    </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { h } from "vue";
import nextApi, { PackagingListRes } from "@/api/nextApi";
import PackagingAdd from "./components/packagingAdd.vue";
import PackagingDetail from "./components/packagingDetail.vue";
import config from "@/utils/config";
@Component({
    name: "productionManagementIndex",
    components: { PackagingAdd, PackagingDetail },
})
export default class extends Vue {
    keywords = "";
    loading = false;
    pagination = {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    modalOption = {
        title: "增加投料量",
        okText: "确定",
        cancelText: "取消",
        loading:false,
        onOk: () => {
            this.addInputConfirm();
        },
        onCancel: () => {
           this.addInputClose();
        },
    };
    addInputForm = {
        putIntoNum: 0,
    };
    addInputFormRules = {
        putIntoNum: [{ required: true, message: "请输入投料量" }],
    }
    pageList: PackagingListRes[] = [];
    columns = [
        {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center",
            customRender: (text: string, record: any, index: number) => `${index + 1}`,
        },
        {
            align: "center",
            dataIndex: "varietyName",
            key: "varietyName",
            title: "名称",
        },
        {
            align: "center",
            dataIndex: "productType",
            key: "productType",
            title: "产品类型",
        },
        {
            align: "center",
            dataIndex: "color",
            key: "color",
            title: "色卡标识",
            customRender: (text: string, record: any, index: number) =>
                h("div", {
                    style: {
                        height: "40px",
                        width: "40px",
                        background: record.colorChart,
                        margin: "auto",
                        borderRadius: "4px",
                    },
                }),
        },
        {
            align: "center",
            dataIndex: "advocateBatch",
            key: "advocateBatch",
            title: "主批号",
        },
        // {
        //     align: "center",
        //     dataIndex: "secondBatch",
        //     key: "secondBatch",
        //     title: "亚批号",
        // },
        {
            align: "center",
            dataIndex: "productBatch",
            key: "productBatch",
            title: "产品批号",
        },
        {
            align: "center",
            dataIndex: "discretion",
            key: "discretion",
            title: "装量",
            customRender: (text: string, record: PackagingListRes, index: number) => record.discretion,
        },
        {
            align: "center",
            dataIndex: "productionTime",
            key: "productionTime",
            title: "生产日期",
        },
        {
            align: "center",
            dataIndex: "expirationDate",
            key: "expirationDate",
            title: "保质期(月)",
        },
        {
            align: "center",
            dataIndex: "putIntoNum",
            key: "putIntoNum",
            title: "投料量",
            customRender: (text: string, record: PackagingListRes, index: number) => record.putIntoNum + record.unit,
        },
        {
            align: "center",
            dataIndex: "medicineClass",
            key: "medicineClass",
            title: "中药等级",
            customRender: (text, record, index) => `${record.medicineClass?record.medicineClass:'-'}`,
        },
        {
            align: "center",
            dataIndex: "productBigKind",
            key: "productBigKind",
            title: "产品大类",
        },
        {
            align: "center",
            dataIndex: "subpackageState",
            key: "subpackageState",
            title: "分包状态",
            customRender: (text: any, record: PackagingListRes) => {
                const obj: { [key: number]: { title: string; class: string } } = {
                    0: { title: "待分包", class: "" },
                    1: { title: "待审核", class: "c-warning" },
                    2: { title: "已通过", class: "c-success" },
                    3: { title: "已驳回", class: "c-danger" },
                };
                const stautsObj = obj[record.subpackageState] || { title: "--", class: "" };
                return h("div", { class: stautsObj.class }, stautsObj.title);
            },
        },
        {
            align: "center",
            dataIndex: "action",
            key: "action",
            title: "操作",
            customRender: (text: string, record: PackagingListRes, index: number) => {
                const detailBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "eye", type: "primary", size: "small" },
                        on: { click: () => this.showDetail(record) },
                    },
                    "查看"
                );
                const editBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "edit", type: "primary", size: "small" },
                        on: { click: () => this.editDetail(record) },
                    },
                    "编辑"
                );
                const addInputBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "5px",},
                        props: { icon: "edit", type: "primary", size: "small" },
                        on: { click: () => this.addInput(record) },
                    },
                    "调整投料量"
                );
                const removeBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "5px"},
                        props: { icon: "delete", type: "danger", size: "small" },
                        on: { click: () => this.remove(record) },
                    },
                    "删除"
                );
                const btn: any[] = [];
                if (this.$utilCheckPermission(["packagingManagementDetails"])) btn.push(detailBtn);
                if (record.subpackageState===0 &&  this.$utilCheckPermission(["packagingManagementCompile"])) btn.push(editBtn);
                if (this.$utilCheckPermission(["packagingManagementAdjustInput"])) btn.push(addInputBtn);
                if (this.$utilCheckPermission(["packagingManagementRemove"])) btn.push(removeBtn);  
                return h("div", btn);
            },
        },
    ];

    getRowKey(item: any) {
        return item.id;
    }
    tabsData = [
        {name:'中药饮片',rawType:'中药饮片(半成品)'},
        {name:'直服饮片',rawType:'直服饮片(半成品)'},
        {name:'单方饮片',rawType:'单方饮片(半成品)'},
    ]
    tabKey = this.tabsData[0].name
    rawType = this.tabsData[0].rawType
    async changeTab(key: number) {
        this.tabKey = this.tabsData[key].name
        this.rawType = this.tabsData[key].rawType
        await this.getList();
    }
    async getList() {
        this.pageList = [];
        try {
            this.loading = true;
            const res = await nextApi.gePackagingList({
                pageSize: this.pagination.pageSize,
                pageNum: this.pagination.current,
                varietyName: this.keywords,
                productType:this.tabKey
            });
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.rows || [];
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    detailVisible = false;
    infoData = {} as PackagingListRes;
    async showDetail(item: PackagingListRes) {
        this.loading = true;
        try {
            const res = await nextApi.getPackagingDetail({ id: item.id });
            this.infoData = { ...res.data };
            this.detailVisible = true;
        } finally {
            this.loading = false;
        }
    }

    addVisible = false;
    infoId = "";
    editDetail(item: PackagingListRes) {
        this.infoId = item.id;
        this.addVisible = true;
    }
    add() {
        this.infoId = "";
        this.addVisible = true;
    }
    addId = "";
    addInputVisible = false;
    addInput(record: PackagingListRes){
        this.addId = record.id;
        this.addInputVisible = true;
        this.addInputForm.putIntoNum = record.putIntoNum
    }
    addInputConfirm(){
        (this.$refs.form as any).validate(async (valid) => {
            if(valid){
                this.modalOption.loading = true
                try {
                    let params = {
                        id:this.addId,
                        putIntoNum:this.addInputForm.putIntoNum,
                    }
                    const res = await nextApi.addInput(params)
                    this.$message.success(res.msg)
                    await this.getList()
                }catch (e) {
                    throw e
                }finally {
                    this.modalOption.loading = false
                    this.addInputVisible = false
                }
            }
        })
    }
    addInputClose(){
        this.addInputVisible = false;
        this.addId = "";
    }
    remove(record: PackagingListRes){
        this.$confirm({
            title: "提示",
            content: "确定删除该包装吗？",
            okText: "确定",
            cancelText: "取消",
            onOk: async () => {
                await nextApi.removePack(record.id)
                this.$message.success("删除成功")
                await this.getList()
            },
            onCancel: () => {
                this.$message.info("取消删除")
            }
        })
    }
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;

        this.getList();
    }
    async mounted() {
        this.getList();
    }
}
</script>
<style lang="scss">
.packaging-index {
    padding: 20px;
}
</style>
